#include <cstdlib>

#include "starfield.h"
/*
// Colorise le pixel en {x,y} sur la surface surface avec la couleur color
void putpixel(SDL_Surface *surface, int x, int y, Uint32 color)
{
	int bpp = surface->format->BytesPerPixel;
	Uint8 *p = (Uint8 *)surface->pixels + y * surface->pitch + x * bpp;

	switch(bpp) {
	case 1:
		*p = color;
		break;

	case 2:
		*(Uint16 *)p = color;
		break;

	case 3:
		if(SDL_BYTEORDER == SDL_BIG_ENDIAN) {
			p[0] = (color >> 16) & 0xff;
			p[1] = (color >> 8) & 0xff;
			p[2] = color & 0xff;
		} else {
			p[0] = color & 0xff;
			p[1] = (color >> 8) & 0xff;
			p[2] = (color >> 16) & 0xff;
		}
		break;

	case 4:
		*(Uint32 *)p = color;
		break;
	}
}
*/
Starfield::Starfield(const int size, const int delay)
:starfield(size)
{
	initStarfield();

	timer = new QTimer(this);
	connect(timer, SIGNAL(timeout()), this, SLOT(updateStarfield()));
	timer ->start(delay);
}

void Starfield::drawStarfield(SDL_Surface *s, Uint32 col) const
{
	SDL_FillRect(s, NULL, 0);

	int w = s->w;
	int hw = w >> 1;
	int h = s->h;
	int hh = h >> 1;

	for(StarFieldContent::const_iterator it = starfield.begin();
		it != starfield.end();
		++it)
	{
		int screenX = static_cast<int>((it->x / it->z) * w + hw);
		int screenY = static_cast<int>((it->y / it->z) * h + hh);

		// ignore out of view stars
		if(screenX < 0 || screenX > 319 || screenY < 0 || screenY > 199)
			continue;

		putpixel(s, screenX, screenY, col);
	}
}

Starfield::Star Starfield::generateStar() const
{
	Star s = {(::rand() / (static_cast<double>(RAND_MAX) + 1.0)) * 20-10,
			(::rand() / (static_cast<double>(RAND_MAX) + 1.0)) * 20-10,
			(::rand() / (static_cast<double>(RAND_MAX) + 1.0)) * 100};
	return s;
}

void Starfield::initStarfield()
{
	for(StarFieldContent::iterator it = starfield.begin();
		it != starfield.end();
		++it)
	{
		*it = generateStar();
	}
}

void Starfield::updateStarfield()
{
	for(StarFieldContent::iterator it = starfield.begin();
		it != starfield.end();
		++it)
	{
		--it->z;

		if(it->z <= 0)
		{
			*it = generateStar();
		}
	}

	emit starfieldUpdated();
}
